﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AgencyEntityLib.BaseEntity;
using Ecopsy.Tools;
using Ecopsy.DataTier;
using AgencyEntityLib.Context;
using System.Data.SqlClient;


namespace AgencyEntityLib.BaseEntity
{
    public class wsAgency:EntitySingle 
    {
        public const string wsKey_CurrentAgency = "CurrentAgency";
        public const string wsKey_CurrentEmployeer = "CurrentEmployeer";

        public wsAgency()
        {
            //Uncomment the following line if using designed components 
            //InitializeComponent(); 
        }


        /// <summary>
        /// Возвращеат агентсво соответсв. текущему пользователю системы.
        /// </summary>
        /// <returns></returns>

        public Agency GetAgency()
        {
            Func<string> F = delegate()
            {
                return "";
            };

            // пользователь идентифизирован
            if (!HttpContext.Current.User.Identity.IsAuthenticated) return null;


            string ID = wsKey_CurrentAgency;


            if (HttpContext.Current.Session == null) ///Запрос вэб службы грузим агентсво и кэшируем не в сессии ?
            {
                if (!CacheTools.IsCacheObject(ID))
                {
                    Agency a = GetAgency(GetAgencyId());
                    CacheTools.SetCacheObject(ID, a);
                    return a;
                }
                else
                    return (Agency)CacheTools.GetCacheObect(ID);
            }

            if (!CacheTools.IsSessionCacheObject(ID))
            {
                Agency a = GetAgency(GetAgencyId());
                CacheTools.SetSessionCacheObject(ID, a);
                return a;
            }

            return (Agency)CacheTools.GetSessionCacheObect(ID);

        }


        public  Agency GetAgency(string AgencyId)
        {
            if (string.IsNullOrEmpty(AgencyId))
                return null;

            AgencyEntityLib.BaseEntity.Agency r = new AgencyEntityLib.BaseEntity.Agency();
            r.ID = AgencyId;
            r.Load();
            return r;

        }

        /// <summary>
        /// Вернуть ид агентсва - которому соответсвует текущий пользователь 
        /// Если определена функция AgencyLib_GlobalConstants._getAgencyId() - вернуть ее результат 
        /// </summary>
        /// <returns></returns>
        private string GetAgencyId()
        {
            //if (AgencyLib_GlobalConstants._getAgencyId != null)
            //    return AgencyLib_GlobalConstants._getAgencyId();

            SqlConnection Conn = null;
            try
            {
                SecuretyContext SC = AppContext.GetSC(AppContext.AppSCPref);
                Conn = SC.Connection;
                if (Conn.State == System.Data.ConnectionState.Closed) Conn.Open();
                SqlCommand cmd = new SqlCommand("select top 1 AgencyId  from v_employee", Conn);
                cmd.CommandType = System.Data.CommandType.Text;
                object r = cmd.ExecuteScalar();
                return r.ToString();
            }

            catch
            {
                return string.Empty;
            }
            finally
            {
                Conn.Close();
            }

        }

        /// <summary>
        /// Возворащает сотрудника соответсвующего текущему логину системы
        /// </summary>
        /// <returns></returns>

        public Employeer GetCurrentEmployeer()
        {
            if (!HttpContext.Current.User.Identity.IsAuthenticated) return null;

            if (!CacheTools.IsSessionCacheObject(HttpContext.Current.User.Identity.Name))
            {
                Employeer Empl = GetEmployeerByLogin(HttpContext.Current.User.Identity.Name);

                CacheTools.SetSessionCacheObject(HttpContext.Current.User.Identity.Name, Empl);
            }
            return (Employeer)CacheTools.GetSessionCacheObect(HttpContext.Current.User.Identity.Name);
        }


        public Employeer GetEmployeerByLogin(string Login)
        {
            Employeer Empl = new Employeer();
            Empl.ID = null;
            Empl.Login = Login;
            Empl.Load();
            return Empl;
        }

        /// <summary>
        /// Сбросить закэшированных для сеанса - текущее агентство и текущий сотрудник
        /// </summary>
        /// <returns></returns>

        public static void Reset()
        {
            CacheTools.ResetSessionCache(wsKey_CurrentAgency);
            CacheTools.ResetSessionCache(wsKey_CurrentEmployeer);
        }




        public SurfaceGroup GetSurfaceGroup(string ID)
        {
            Agency a = GetAgency();
            if (null != a.SurfaceGroups[ID]) return (SurfaceGroup)a.SurfaceGroups[ID];

            if (!CacheTools.IsCacheObject(ID))
            {
                SurfaceGroup r = new SurfaceGroup();
                r.ID = ID;
                if (r.Name.Equals(string.Empty)) r.Name = "Новая группа";
                CacheTools.SetCacheObject(ID, r);
                return r;
            }
            return (SurfaceGroup)CacheTools.GetCacheObect(ID);
        }


        public SiteMapItem GetSiteMapItem(string ID)
        {
            Agency a = GetAgency();
            if (null != a.SitMap[ID]) return (SiteMapItem)a.SitMap[ID];

            if (!CacheTools.IsCacheObject(ID))
            {
                SiteMapItem r = new SiteMapItem();
                r.ID = ID;
                if (r.Key.Equals(string.Empty)) r.Key = "";
                CacheTools.SetCacheObject(ID, r);
                return r;
            }
            return (SiteMapItem)CacheTools.GetCacheObect(ID);
        }


        public SiteMapItem SaveSiteMapItem(SiteMapItem _SiteMapItem)
        {
            Agency a = GetAgency();

            if (_SiteMapItem.ID.IndexOf(AgencyLib_GlobalConstants.qPrefNEW_RECORD) > -1)//режим вставки?
            {
                string s = _SiteMapItem.ID;
                _SiteMapItem.ID = _SiteMapItem.ID.Replace(AgencyLib_GlobalConstants.qPrefNEW_RECORD, "");
                CacheTools.ResetCache(s);
            }

            a.SitMap.Remove(_SiteMapItem.ID);
            a.SitMap.Add(_SiteMapItem);
            SaveAgency();
            return GetSiteMapItem(_SiteMapItem.ID);

        }


        public Discount GetDiscount(string ID)
        {
            Agency a = GetAgency();
            if (null != a.Discounts[ID]) return (Discount)a.Discounts[ID];

            if (!CacheTools.IsCacheObject(ID))
            {
                Discount r = new Discount();
                r.ID = ID;
                if (r.Name.Equals(string.Empty)) r.Name = "Новая скидка";
                r.dtStart = DateTime.Now;
                r.dtFinish = DateTime.Now.AddMonths(1);
                CacheTools.SetCacheObject(ID, r);
                return r;
            }
            return (Discount)CacheTools.GetCacheObect(ID);
        }


        public SurfaceGroup SaveSurfaceGroup(SurfaceGroup _SurfaceGroup)
        {
            Agency a = GetAgency();

            if (_SurfaceGroup.ID.IndexOf(AgencyLib_GlobalConstants.qPrefNEW_RECORD) > -1)//режим вставки?
            {
                string s = _SurfaceGroup.ID;
                _SurfaceGroup.ID = _SurfaceGroup.ID.Replace(AgencyLib_GlobalConstants.qPrefNEW_RECORD, "");
                CacheTools.ResetCache(s);
            }

            a.SurfaceGroups.Remove(_SurfaceGroup.ID);
            a.SurfaceGroups.Add(_SurfaceGroup);
            SaveAgency();
            return GetSurfaceGroup(_SurfaceGroup.ID);

        }


        public Discount SaveDiscount(Discount _Discount)
        {
            Agency a = GetAgency();

            if (_Discount.ID.IndexOf(AgencyLib_GlobalConstants.qPrefNEW_RECORD) > -1)//режим вставки?
            {
                string s = _Discount.ID;
                _Discount.ID = _Discount.ID.Replace(AgencyLib_GlobalConstants.qPrefNEW_RECORD, "");
                CacheTools.ResetCache(s);
            }

            a.Discounts.Remove(_Discount.ID);
            a.Discounts.Add(_Discount);
            SaveAgency();
            return GetDiscount(_Discount.ID);

        }


        public SuraceGroupList GetSurfaceGroupList(SuraceGroupList.sqlLoadStatment WhereStatment)
        {
            SuraceGroupList list = new SuraceGroupList();
            list.SqlStatment = WhereStatment;
            list.Load();
            return list;
        }

        public DiscountList GetSurfaceGroupList(DiscountList.sqlLoadStatment WhereStatment)
        {
            DiscountList list = new DiscountList();
            list.SqlStatment = WhereStatment;
            list.Load();
            return list;
        }

        public void SaveAgency(Agency a)
        {
            a.Save();

        }

        public void SaveAgency()
        {
            Agency a = GetAgency();
            a.Save();
            CacheTools.ResetCache(a.ID);
        }

        #region Department

        public void RemoveDepartment(string DepartmentID)
        {
            Agency a = GetAgency();
            Department d = (Department)a.Department.Find(DepartmentID);
            d.DestroyMySelf();
        }

        public Department AddDepartment(string ParentDepartmentID, string DepartmentName)
        {
            try
            {
                Department d = new Department { Name = DepartmentName };
                Department p = GetDepartment(ParentDepartmentID);
                p.ChildNodes.Add(d);
                return d;
            }
            catch
            {
                throw;

            }

        }

        /// <summary>
        /// Вернуть ветку дерева агентсва
        /// </summary>
        /// <param name="FolderId"></param>
        /// <param name="TreeDictionaryID"></param>
        /// <param name="BranchID"></param>
        /// <returns></returns>

        public Department GetDepartment(string DepartmentID)
        {
            try
            {
                Agency a = GetAgency();
                Department d = (Department)a.Department;
                return (Department)d.Find(DepartmentID);
            }
            catch
            {
                return null;
            }

        }
        #endregion

        #region  Emploers
        /// <summary>
        /// Вернуть нового сотрудника и держать ео в кэше пока не прикрепят к какому либо списку
        /// </summary>
        /// <param name="EmplID"></param>
        /// <returns></returns> 

        private static Employeer GetNewEmpl(string EmplID)
        {
            if (HttpContext.Current.Cache[EmplID] == null)
            {
                Employeer p = new Employeer();
                p.ID = EmplID;
                HttpContext.Current.Cache.Add(EmplID, p, null, DateTime.MaxValue, TimeSpan.FromMinutes(10), System.Web.Caching.CacheItemPriority.Normal, null);
                return p;
            }

            return (Employeer)HttpContext.Current.Cache[EmplID];

        }



        #endregion



    }
}

